﻿using System;
using System.Configuration;
using System.Data.Linq;
using System.Linq;
using System.Collections.Generic;

namespace StackBookL2S
{
    public class L2SStackBookRepository : StackBookLib.Interfaces.IStackBookRespository
    {
        protected DataContext dc;

        public Table<StackBookLib.Model.Account> Accounts { get; set; }

        public L2SStackBookRepository()
        {
            dc = new DataContext(ConfigurationManager.ConnectionStrings["StackBookConnectionString"].ConnectionString, ObjectMapping.GetMapping("StackBookL2S.AccountMapping.xml"));
            Accounts = dc.GetTable<StackBookLib.Model.Account>();
        }

        public IEnumerable<StackBookLib.Model.Account> GetAccounts()
        {
            return Accounts;
        }

        public StackBookLib.Model.Account GetByFacebookId(long facebookUid)
        {
            var item = Accounts.SingleOrDefault(f => f.FacebookId == facebookUid);
            if (item == null)
            {
                item = new StackBookLib.Model.Account();
                item.FacebookId = facebookUid;
                item.LastUpdate = DateTime.Now;
                Accounts.InsertOnSubmit(item);
                dc.SubmitChanges();
            }
            return item;
        }

        public void SetFacebookAssociation(long facebookUid, int stackoverflowUid)
        {
            var item = Accounts.Single(f => f.FacebookId == facebookUid);
            if (item != null)
            {
                item.StackOverflowId = stackoverflowUid;
                dc.SubmitChanges();
            }
        }

        public void RemoveFacebookAssociation(long facebookUid)
        {
            var item = Accounts.Single(f => f.FacebookId == facebookUid);
            if (item != null)
            {
                item.StackOverflowId = null;
                dc.SubmitChanges();
            }
        }

        public void SetLastUpdate(int accountId, DateTime updateTime)
        {
            var item = Accounts.Single(f => f.AccountId == accountId);
            if (item != null)
            {
                item.LastUpdate = updateTime;
                dc.SubmitChanges();
            }
        }
    }
}
